package br.ufpe.cin.msc.jrsj2.recommender.message;

import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

public abstract class ApplicationMessage {

	protected static String requestMessage;
	protected static String responseMessage;
	protected MessageParser messageParser;

	public ApplicationMessage() {
		this.messageParser = new MessageParser();
	}

	private class MessageParser extends DefaultHandler {
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) {
			try {
				parseMessageElement(uri, localName, qName, attributes);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void characters(char[] ch, int start, int length) {
			try {
				parseMessageContent(ch, start, length);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName) {
			try {
				parseMessageEndElement(uri, localName, qName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void setRequestMessage(String requestMessage) {
		ApplicationMessage.requestMessage = requestMessage;
	}

	public static void setResponseMessage(String reponseMessage) {
		ApplicationMessage.responseMessage = reponseMessage;
	}

	public static String getResponseMessage() {
		return ApplicationMessage.responseMessage;
	}

	public void parseRequestMessage() {
		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			InputSource is = new InputSource(new StringReader(requestMessage));
			parser.parse(is, messageParser);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	protected abstract void buildResponseMessage(List objects);

	protected abstract void parseMessageElement(String uri, String localName,
			String qName, Attributes attributes);

	protected abstract void parseMessageContent(char[] ch, int start, int length);

	protected abstract void parseMessageEndElement(String uri,
			String localName, String qName);

}
